/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package databases;

import javax.swing.table.DefaultTableModel;
import Conexion.Conecxion;
import com.sun.corba.se.spi.orb.StringPair;
import com.sun.xml.internal.fastinfoset.EncodingConstants;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author Admin
 */
public class Pedido extends javax.swing.JFrame {
    DefaultTableModel Modelo;
    DefaultTableModel Model;
    private String Codigo_Global;
    private int Cont;
    static Conecxion CP;
    /**
     * Creates new form Pedido
     */
    public Pedido(Conecxion Cp) {
        this.CP=Cp;
        initComponents();
        
        MostrarCombo();
       Modelo=new DefaultTableModel();
       Modelo.addColumn("Codigo");
       Modelo.addColumn("Direccion");
       Modelo.addColumn("Cliente");
       this.TablaPedido.setModel(Modelo);
       Model=new DefaultTableModel();
//       Model.addColumn("Id Pedido");
       Model.addColumn("Articulo");
       Model.addColumn("Cantidad");
       Model.addColumn("Linea");
       this.TablaDetalle.setModel(Model);
       Actualizar();
       
        Nombres();
        
    }
    
    private void MostrarCombo()
    {
        
       
        this.ComboCliente.removeAllItems();
        
          try {
              
            ResultSet datos = this.CP.select("*", "\"schQuiz2\".cliente", "");
        
            this.ComboCliente.addItem("Buscar...");
            while (datos.next()) {
//                this.TablaDeDatos.add(datos.getString(1)+" "+datos.getString(2) +" "+ datos.getString(3) + "\n");
                
                
               //String cliente= datos.getString(6);
              
                this.ComboCliente.addItem(datos.getString(6));
            
            }
            
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString()+"\n");
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TablaPedido = new javax.swing.JTable();
        Codigo = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        Direccion = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        Insertar = new javax.swing.JButton();
        Actualizar = new javax.swing.JButton();
        Borrar = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        ComboCliente = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        TablaDetalle = new javax.swing.JTable();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        Articulo = new javax.swing.JTextField();
        Cantidad = new javax.swing.JTextField();
        Agregar = new javax.swing.JButton();
        Modificar = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Pedido");

        TablaPedido.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        TablaPedido.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TablaPedidoMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(TablaPedido);

        jLabel2.setText("Codigo");

        jLabel3.setText("Direccion");

        jLabel4.setText("Cliente");

        Insertar.setText("Insertar");
        Insertar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                InsertarActionPerformed(evt);
            }
        });

        Actualizar.setText("Actualizar");
        Actualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ActualizarActionPerformed(evt);
            }
        });

        Borrar.setText("Borrar");
        Borrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BorrarActionPerformed(evt);
            }
        });

        jButton1.setText("Atras");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        ComboCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ComboClienteActionPerformed(evt);
            }
        });

        TablaDetalle.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        TablaDetalle.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TablaDetalleMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(TablaDetalle);

        jLabel5.setText("Detalle De Pedido");

        jLabel7.setText("Articulo");

        jLabel8.setText("Cantidad");

        Articulo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                ArticuloMouseEntered(evt);
            }
        });
        Articulo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ArticuloActionPerformed(evt);
            }
        });

        Agregar.setText("Agregar");
        Agregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AgregarActionPerformed(evt);
            }
        });

        Modificar.setText("Modificar");
        Modificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ModificarActionPerformed(evt);
            }
        });

        btnDelete.setText("Eliminar");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jButton1)
                        .addGap(138, 138, 138)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 417, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(Direccion, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(ComboCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel5)
                        .addGap(149, 149, 149))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(92, 92, 92)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(17, 17, 17)
                                        .addComponent(Agregar)
                                        .addGap(48, 48, 48)
                                        .addComponent(Modificar)
                                        .addGap(60, 60, 60)
                                        .addComponent(btnDelete))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(layout.createSequentialGroup()
                                                .addGap(17, 17, 17)
                                                .addComponent(jLabel7))
                                            .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING))
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(Articulo, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(Cantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                .addGap(0, 67, Short.MAX_VALUE))))))
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(Insertar)
                .addGap(43, 43, 43)
                .addComponent(Actualizar)
                .addGap(48, 48, 48)
                .addComponent(Borrar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(Direccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(ComboCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Articulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(Insertar)
                            .addComponent(Actualizar)
                            .addComponent(Borrar))
                        .addGap(51, 51, 51))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(Cantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel8))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Agregar)
                    .addComponent(Modificar)
                    .addComponent(btnDelete))
                .addGap(43, 43, 43))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    
        private void Actualizar()
    {
         
        int CantidadFilas=TablaPedido.getRowCount();
        for(int i=CantidadFilas-1;i>=0;i--)
        {
            Modelo.removeRow(i);
        }
        
          try {
              
            ResultSet datos = this.CP.select("*", "\"schQuiz2\".pedido", "");
            String[]Arreglo=new String[3];
            
            while (datos.next()) {
//                this.TablaDeDatos.add(datos.getString(1)+" "+datos.getString(2) +" "+ datos.getString(3) + "\n");
                
                Arreglo[0]=datos.getString(1);
                Arreglo[1]=datos.getString(2);
                Arreglo[2]=datos.getString(3);
              
                Modelo.addRow(Arreglo);
            }
            
            System.out.println("Actualizado");
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString()+"\n");
        }
       
    }
        private int contador()
        {
      
            int Dato=0;
          try {
              
            ResultSet datos = this.CP.select("count(*)", "\"schQuiz2\".detalle_pedido", "pedido= "+Codigo_Global);
         
            
            while (datos.next()) {
//                this.TablaDeDatos.add(datos.getString(1)+" "+datos.getString(2) +" "+ datos.getString(3) + "\n");
                
               Dato=Integer.parseInt( datos.getString(1));
                

            }
            
            
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString()+"\n");
        }
         
          return Dato;
        }
        
           private int CuentaMax()
        {
      
            int Dato=0;
          try {
              
            ResultSet datos = this.CP.select("max(linea)", "\"schQuiz2\".detalle_pedido", "pedido= "+Codigo_Global);
         
            
            while (datos.next()) {
//                this.TablaDeDatos.add(datos.getString(1)+" "+datos.getString(2) +" "+ datos.getString(3) + "\n");
                
               Dato=Integer.parseInt( datos.getString(1));
                

            }
            
            
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString()+"\n");
        }
         
          return Dato;
        }
        
           private boolean EncontroLinea(String Linea)
           {
               boolean Estado=false;
              ResultSet datos = this.CP.select("linea", "\"schQuiz2\".detalle_pedido", "pedido= "+Codigo_Global);
            
            int pasadas=0;
        try {
            while (datos.next()) {
                
                if(Linea.equalsIgnoreCase(datos.getString(1)))
                {
                    Estado=true;
                }
                
            }
        } catch (SQLException ex) {
            Logger.getLogger(Pedido.class.getName()).log(Level.SEVERE, null, ex);
        }
        return  Estado;
            }
           
           
                      private String TraerArticulo(String Linea)
           {
               String Estado="";
              ResultSet datos = this.CP.select("articulo", "\"schQuiz2\".detalle_pedido", "pedido= "+Codigo_Global+" and "+"linea ="+Linea);

        try {
            while (datos.next()) {
                
              
                    Estado=datos.getString(1);
               
                
            }
        } catch (SQLException ex) {
            Logger.getLogger(Pedido.class.getName()).log(Level.SEVERE, null, ex);
        }
        return  Estado;
            }
           
                      
                                 
                      private String TraerCantidad(String Linea)
           {
               String Estado="";
              ResultSet datos = this.CP.select("cantidad", "\"schQuiz2\".detalle_pedido", "pedido= "+Codigo_Global+" and "+ "linea = "+Linea);
           
        try {
            while (datos.next()) {
                
                
                    Estado=datos.getString(1);
                
                
            }
        } catch (SQLException ex) {
            Logger.getLogger(Pedido.class.getName()).log(Level.SEVERE, null, ex);
        }
        return  Estado;
            }
        private void Actualizar2()
        {
            
            
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////7

            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////7
                    int CantidadFilas=TablaDetalle.getRowCount();
        for(int i=CantidadFilas-1;i>=0;i--)
        {
            Model.removeRow(i);
        }
        
        
          try {
              
            ResultSet datos = this.CP.select("*", "\"schQuiz2\".detalle_pedido", "pedido= "+Codigo_Global);
            String[]Arreglo=new String[3];
            int pasadas=0;
            while (datos.next()) {
//                this.TablaDeDatos.add(datos.getString(1)+" "+datos.getString(2) +" "+ datos.getString(3) + "\n");
                
//                Arreglo[0]=datos.getString(1);
//                Arreglo[0]=datos.getString(2);

                
                ///////////////////////////////////////////////////////////////////////////////////////////////////
                pasadas++;
                if(!EncontroLinea(String.valueOf(pasadas))==true)
                {
                Arreglo[1]=datos.getString(3);
                Arreglo[2]=String.valueOf(pasadas);
                            boolean 
             Actualiza = this.CP.Actualizar("\"schQuiz2\".detalle_pedido",
                     " pedido = " + Codigo_Global + ", articulo = '"  + datos.getString(2)+"', cantidad = "+datos.getString(3)+", linea = "+pasadas,
                           
                     " pedido = " + Codigo_Global+" and "+"linea = "+datos.getString(4) );  //Ojo Aqui
               
                
                //////////////////////////////////////////////////////////////////////////////////////////////////
                ResultSet dato2=this.CP.select("descripcion", "\"schQuiz2\".articulo", "codigo= '"+datos.getString(2)+"'");
                while(dato2.next()){
                Arreglo[0]=dato2.getString(1);
                
                }
                Model.addRow(Arreglo);
                
                }else
                {
                Arreglo[1]=TraerCantidad(String.valueOf(pasadas));
                Arreglo[2]=String.valueOf(pasadas);
                ResultSet dato2=this.CP.select("descripcion", "\"schQuiz2\".articulo", "codigo= '"+TraerArticulo(String.valueOf(pasadas))+"'");
                while(dato2.next()){
                Arreglo[0]=dato2.getString(1);
                
                }
                Model.addRow(Arreglo);
                
                //Revisar todo esto para cuando sea posible
                
                }
           
//              System.out.println("Dato Actualizado");
//                //////////////////////////////////////////////////////////////////////////////////////////////////
//                ResultSet dato=this.CP.select("descripcion", "\"schQuiz2\".articulo", "codigo= '"+datos.getString(2)+"'");
//                while(dato.next()){
//                Arreglo[0]=dato.getString(1);
//                
//                }
//                Model.addRow(Arreglo);
            }
            
            System.out.println("Actualizado");
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString()+"\n");
        }
        }
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        setVisible(false);
        Tabla T = new Tabla();
        T.setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    private String Retorne(String Combo) throws SQLException
    {
        ResultSet datos=this.CP.select("codigo", "\"schQuiz2\".cliente", "descripcion = '"+Combo+"'");
        datos.next();
        String Codigito=datos.getString(1);
        return Codigito;
    }
    
    private String Escribir(String dato) throws SQLException
    {
        String Codigito="";
        ResultSet datos=this.CP.select("descripcion", "\"schQuiz2\".cliente", "codigo = "+dato);
        while(datos.next()){
        Codigito=datos.getString(1);
    }
        return Codigito;
    }
    private void InsertarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InsertarActionPerformed
        // TODO add your handling code here:
        
        
       
              Actualizar();
                try {
            boolean Insertar = this.CP.Insert("\"schQuiz2\".pedido", this.Codigo.getText()+", '"+this.Direccion.getText()+"', "+Retorne(this.ComboCliente.getSelectedItem().toString()));
               
              Actualizar();
            
              Nombres();
                   
                   
           
              System.out.println("Dato Insertado");
            
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString());
        }
    }//GEN-LAST:event_InsertarActionPerformed

    private void Codigos()
    {
        int Seleccion=this.TablaPedido.getRowCount();
           for(int i= 0;i<=Seleccion-1;i++)
                   {
             try {
                 this.Modelo.setValueAt(Retorne(this.TablaPedido.getValueAt(i, 2).toString()), i, 2);
             } catch (SQLException ex) {
                 Logger.getLogger(Pedido.class.getName()).log(Level.SEVERE, null, ex);
             }
                   }
        
    }
    private void Nombres()
    {
        int Seleccion=this.TablaPedido.getRowCount();
        
//        for(int i =0;i<=Seleccion-1;i++)
//        {
//            try {
//                this.Modelo.setValueAt(Retorne(this.TablaPedido.getValueAt(i, 2).toString()), i, 2);
//            } catch (SQLException ex) {
//                Logger.getLogger(Pedido.class.getName()).log(Level.SEVERE, null, ex);
//            }
//        }
        
        
         
                   for(int i= 0;i<=Seleccion-1;i++)
                   {
             try {
                 this.Modelo.setValueAt(Escribir(this.TablaPedido.getValueAt(i, 2).toString()), i, 2);
             } catch (SQLException ex) {
                 Logger.getLogger(Pedido.class.getName()).log(Level.SEVERE, null, ex);
             }
                   }
    }
    private void ActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ActualizarActionPerformed
        // TODO add your handling code here:}
        
//        Actualizar();
          String Dato="";
                    try {
              
            ResultSet datos = this.CP.select("*", "\"schQuiz2\".pedido", "");
           
            
             int Pasadas=0;
             int Columnas=TablaPedido.getSelectedRow();
            while (datos.next()) {
//                this.TablaDeDatos.add(datos.getString(1)+" "+datos.getString(2) +" "+ datos.getString(3) + "\n");
              
                if(Pasadas==Columnas)
                {
                datos.getString(1);
              
              

                Dato=datos.getString(1);
                }
                
                Pasadas++;
            }
               
            System.out.println("Recorrido");
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString()+"\n");
        }
       
     
            try {
            boolean 
             Actualiza = this.CP.Actualizar("\"schQuiz2\".pedido",
                     " codigo = " + this.Codigo.getText() + ", direccion= '"  + this.Direccion.getText()+"', cliente = "+Retorne(this.ComboCliente.getSelectedItem().toString()),
                           
                     " codigo = " + Dato );  //Ojo Aqui
                   
           
              System.out.println("Dato Actualizado");
              Actualizar();
//              SetTexfield();
              Nombres();
           
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString()+"\n");
        }
        
    }//GEN-LAST:event_ActualizarActionPerformed

    private void BorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BorrarActionPerformed
        // TODO add your handling code here:
        
        String Dato="";
                    try {
              
            ResultSet datos = this.CP.select("*", "\"schQuiz2\".pedido", "");
           
            
             int Pasadas=0;
             int Columnas=TablaPedido.getSelectedRow();
            while (datos.next()) {
//                this.TablaDeDatos.add(datos.getString(1)+" "+datos.getString(2) +" "+ datos.getString(3) + "\n");
              
                if(Pasadas==Columnas)
                {
                datos.getString(1);
                datos.getString(2);
                datos.getString(3);
             
                Dato=datos.getString(1);
                }
                
                Pasadas++;
            }
                
            System.out.println("Vista De Datos");
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString()+"\n");
        }
        
        
            try {
            boolean 
             Delete = this.CP.Delete("\"schQuiz2\".pedido","codigo = "+Dato);
                     
                   
           
              System.out.println("Dato Borrado");
            Actualizar();
            Nombres();
//            SetTexfield();
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString());
        }
    }//GEN-LAST:event_BorrarActionPerformed

    private void ComboClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ComboClienteActionPerformed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_ComboClienteActionPerformed

    private void TablaPedidoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TablaPedidoMouseClicked
        // TODO add your handling code here:
        
//                Codigo_Global="";
        String Dato="";
                    try {
              
            ResultSet datos = this.CP.select("*", "\"schQuiz2\".pedido", "");
           
            
             int Pasadas=0;
             int Columnas=TablaPedido.getSelectedRow();
            while (datos.next()) {
//                this.TablaDeDatos.add(datos.getString(1)+" "+datos.getString(2) +" "+ datos.getString(3) + "\n");
              
                if(Pasadas==Columnas)
                {
               String A= datos.getString(1);
               String B= datos.getString(2);
//               String C= datos.getString(3);
             
               this.Codigo_Global=A;
               this.Codigo.setText(A);
               this.Direccion.setText(B);
               this.ComboCliente.setSelectedItem(Escribir(datos.getString(3)));
               
                }
                
           
                Pasadas++;
            }
                
            System.out.println("Datos Cargados");
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString()+"\n");
        }
                    
                    ///////////////////////////////////////////////////////////////////////////////////
                                        int CantidadFilas=TablaDetalle.getRowCount();
        for(int i=CantidadFilas-1;i>=0;i--)
        {
            Model.removeRow(i);
        }
                    Actualizar2();
//        int CantidadFilas=TablaDetalle.getRowCount();
//        for(int i=CantidadFilas-1;i>=0;i--)
//        {
//            Model.removeRow(i);
//        }
//        
//          try {
//              
//            ResultSet datos = this.CP.select("*", "\"schQuiz2\".detalle_pedido", "pedido= "+Codigo_Global);
//            String[]Arreglo=new String[3];
//            
//            while (datos.next()) {
////                this.TablaDeDatos.add(datos.getString(1)+" "+datos.getString(2) +" "+ datos.getString(3) + "\n");
//                
////                Arreglo[0]=datos.getString(1);
////                Arreglo[0]=datos.getString(2);
//                Arreglo[0]=datos.getString(2);
//                Arreglo[1]=datos.getString(3);
//                Arreglo[2]=datos.getString(4);
////                ResultSet dato=this.CP.select("descripcion", "\"schQuiz2\".articulo", "codigo= '"+datos.getString(2)+"'");
////                while(dato.next()){
////                Arreglo[0]=dato.getString(1);
////                
////                }
//                Model.addRow(Arreglo);
//            }
//            
//            System.out.println("Actualizado");
//        } catch (Exception e) {
//            System.out.printf("Error: " + e.toString()+"\n");
//        }
        
        
                    
                    
                    
        
    }//GEN-LAST:event_TablaPedidoMouseClicked

    private boolean SumarValor()
    {
        
        boolean Estado=false;
                ResultSet datos=this.CP.select("*", "\"schQuiz2\".detalle_pedido", "pedido = "+Codigo_Global);
        try {
            while(datos.next())
            {
                String Articulos=datos.getString(2);
                if(Articulos.equalsIgnoreCase(Articulo.getText()))
                {
                    int X=Integer.parseInt(datos.getString(3));
                    int Y=Integer.parseInt(Cantidad.getText());
                   boolean   Actualiza = this.CP.Actualizar("\"schQuiz2\".detalle_pedido",
                     "cantidad = "+(X+Y),
                           
                     " pedido = " + Codigo_Global+" and "+" linea = "+datos.getString(4) );
                    Estado=true;
                    Actualizar2();
                }
                
            }
        } catch (SQLException ex) {
            Logger.getLogger(Pedido.class.getName()).log(Level.SEVERE, null, ex);
        }
       return Estado;
    }
    private void AgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AgregarActionPerformed
        // TODO add your handling code here:
        
        
          
//              Actualizar2();
              if(!SumarValor()==true)
              {
              if(contador()==0)
              {
                  Actualizar2();
                try {
            boolean Insertar = this.CP.Insert("\"schQuiz2\".detalle_pedido", Codigo_Global+", '"+this.Articulo.getText()+"', "+this.Cantidad.getText()+", "+(contador()+1));
               
              Actualizar2();
            
//              Nombres();
                   
                   
           
              System.out.println("Dato Insertado");
            
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString());
        }
              }else
              {
                  Actualizar2();
                         try {
            boolean Insertar = this.CP.Insert("\"schQuiz2\".detalle_pedido", Codigo_Global+", '"+this.Articulo.getText()+"', "+this.Cantidad.getText()+", "+(CuentaMax()+1));
               
              Actualizar2();
            
//              Nombres();
                   
                   
           
              System.out.println("Dato Insertado");
            
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString());
        }
              }
              
              
              }
              else
              {
                  
                  System.out.println("Dato Sumado");
                  Actualizar2();
//                               try {
//                                   boolean Insertar = this.CP.Insert("\"schQuiz2\".detalle_pedido", Codigo_Global+", '"+this.Articulo.getText()+"', "+this.Cantidad.getText()+", "+(contador()+1));
//               
//                                  Actualizar2();
//            
////                                Nombres();
//                   
//                   
//           
//                                  System.out.println("Dato Insertado");
//            
//                                 } catch (Exception e) {
//                                  System.out.printf("Error: " + e.toString());
//        }
              }
    }//GEN-LAST:event_AgregarActionPerformed

    private void ModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ModificarActionPerformed
        // TODO add your handling code here:
                
//        Actualizar();
          String Dato="";
                    try {
              
            ResultSet datos = this.CP.select("*", "\"schQuiz2\".detalle_pedido", "pedido = "+this.Codigo_Global);
           
            
             int Pasadas=0;
             int Columnas=TablaDetalle.getSelectedRow();
            while (datos.next()) {
//                this.TablaDeDatos.add(datos.getString(1)+" "+datos.getString(2) +" "+ datos.getString(3) + "\n");
              
                if(Pasadas==Columnas)
                {
                datos.getString(1);
                datos.getString(2);
                datos.getString(3);
               
              

                Dato=datos.getString(4);
                }
                
                Pasadas++;
            }
               
            System.out.println("Recorrido");
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString()+"\n");
        }
       
     
            try {
            boolean 
             Actualiza = this.CP.Actualizar("\"schQuiz2\".detalle_pedido",
                     " pedido = " + Codigo_Global + ", articulo = '"  + this.Articulo.getText()+"', cantidad = "+this.Cantidad.getText()+", linea = "+Dato,
                           
                     " pedido = " + Codigo_Global+" and "+" linea = "+Dato );  //Ojo Aqui
                   
           
              System.out.println("Dato Actualizado");
              Actualizar2();
//              SetTexfield();
//              Nombres();
//           
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString()+"\n");
        }
        
    }//GEN-LAST:event_ModificarActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        // TODO add your handling code here:
//                Cont=contador()+2;
        String Dato="";
       
                    try {
              
            ResultSet datos = this.CP.select("*", "\"schQuiz2\".detalle_pedido", "pedido= "+Codigo_Global);
           
            
             int Pasadas=0;
             int Columnas=TablaDetalle.getSelectedRow();
            while (datos.next()) {
//                this.TablaDeDatos.add(datos.getString(1)+" "+datos.getString(2) +" "+ datos.getString(3) + "\n");
              
                if(Pasadas==Columnas)
                {
                datos.getString(1);
                datos.getString(2);
                datos.getString(3);
             
                Dato=datos.getString(4);
                }
                
                Pasadas++;
            }
                
            System.out.println("Vista De Datos");
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString()+"\n");
        }
        
        
            try {
            boolean 
             Delete = this.CP.Delete("\"schQuiz2\".detalle_pedido","pedido = "+Codigo_Global+" and"+" linea = "+Dato);
                     
                   
           
              System.out.println("Dato Borrado");
            Actualizar2();
//            Nombres();
//            SetTexfield();
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString());
        }
            
//             Actualizar2();
            
//            
//                          try {
//              
//            ResultSet datos = this.CP.select("*", "\"schQuiz2\".detalle_pedido", "pedido= "+Codigo_Global);
//           
//            
//             int Pasadas=0;
//             int Columnas=TablaDetalle.getSelectedRow();
//            while (datos.next()) {
////                this.TablaDeDatos.add(datos.getString(1)+" "+datos.getString(2) +" "+ datos.getString(3) + "\n");
//              Pasadas++;
//                         try {
//            boolean 
//             Actualiza = this.CP.Actualizar("\"schQuiz2\".detalle_pedido",
//                     " pedido = " + Codigo_Global + ", articulo = '"  + datos.getString(2)+"', cantidad = "+datos.getString(3)+", linea = "+Pasadas,
//                           
//                     " pedido = " + Codigo_Global );  //Ojo Aqui
//                   
//           
//              System.out.println("Dato Actualizado");
//              Actualizar2();
////              SetTexfield();
////              Nombres();
////           
//        } catch (Exception e) {
//            System.out.printf("Error: " + e.toString()+"\n");
//        }
//                
//                
//            }
//                
//            System.out.println("Vista De Datos");
//        } catch (Exception e) {
//            System.out.printf("Error: " + e.toString()+"\n");
//        }
        
    }//GEN-LAST:event_btnDeleteActionPerformed

    
    private String CodigoArticulo(String Descripcion)
    {
        String Codigoo="";
             ResultSet datos = this.CP.select("codigo", "\"schQuiz2\".articulo", "descripcion= '"+Descripcion+"'");
        try {
            while(datos.next())
            {
                Codigoo=datos.getString(1);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Pedido.class.getName()).log(Level.SEVERE, null, ex);
        }
             return Codigoo;
             
    }
    private void TablaDetalleMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TablaDetalleMouseClicked
        // TODO add your handling code here:
        
        int Pasadas=TablaDetalle.getSelectedRow();
        
               String A= CodigoArticulo(this.TablaDetalle.getValueAt(Pasadas, 0).toString());
               String B= this.TablaDetalle.getValueAt(Pasadas, 1).toString();
               this.Articulo.setText(A);
               this.Cantidad.setText(B);
//
//                String Dato="";
//                    try {
//              
//            ResultSet datos = this.CP.select("*", "\"schQuiz2\".detalle_pedido", "pedido= "+Codigo_Global);
//           
//            
//             int Pasadas=0;
//             int Columnas=TablaDetalle.getSelectedRow();
//            while (datos.next()) {
////                this.TablaDeDatos.add(datos.getString(1)+" "+datos.getString(2) +" "+ datos.getString(3) + "\n");
//              
//                if(Pasadas==Columnas)
//                {
//               String A= datos.getString(2);
//               String B= datos.getString(3);
////               String C= datos.getString(3);
//             
//              
//               this.Articulo.setText(A);
//               this.Cantidad.setText(B);
//               
//               
//                }
//                
//           
//                Pasadas++;
//            }
//                
//            System.out.println("Datos Cargados");
//        } catch (Exception e) {
//            System.out.printf("Error: " + e.toString()+"\n");
//        }
    }//GEN-LAST:event_TablaDetalleMouseClicked

    private void ArticuloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ArticuloActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_ArticuloActionPerformed

    private void ArticuloMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ArticuloMouseEntered
        // TODO add your handling code here:
//                Conecxion CP = null;
//        try {
//            CP = new Conecxion("dbQuiz2", "usrUTN", "12345");
//        } catch (ClassNotFoundException ex) {
//            Logger.getLogger(Tabla.class.getName()).log(Level.SEVERE, null, ex);
//        }
//      
//        Cod_Articulo A = new Cod_Articulo(CP);
//        A.setVisible(true);
        
    }//GEN-LAST:event_ArticuloMouseEntered

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Pedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Pedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Pedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Pedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Pedido(CP).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Actualizar;
    private javax.swing.JButton Agregar;
    private javax.swing.JTextField Articulo;
    private javax.swing.JButton Borrar;
    private javax.swing.JTextField Cantidad;
    private javax.swing.JTextField Codigo;
    private javax.swing.JComboBox ComboCliente;
    private javax.swing.JTextField Direccion;
    private javax.swing.JButton Insertar;
    private javax.swing.JButton Modificar;
    private javax.swing.JTable TablaDetalle;
    private javax.swing.JTable TablaPedido;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
}
